 # -*- coding: utf-8 -*-
'''
    视图里面需要定义的方法都定义在这里
'''

import os
import threading
import multiprocessing
from Data import models, databaseApi
from manage import run_spider
from . import reptile
from .tools import get_md5



Book = models.Book
BookInfo = models.BookInfo
User = models.User
UserInfo = models.UserInfo

# 实例化数据库操作引擎
db = databaseApi.API(models.engine)

# 模糊查询类
class FuzzyQuery(object):
    '''人工智障查询，假智能'''
    def __init__(self):
        self.keywords = []
        # 源数据列表
        self.initial = []
        # 较匹配列表
        self.perfect = []
        
    def querys(self, keywords):
        self.keywords = keywords
        # 先查看元数据
        res = self.get_perfect()
        if len(res) > 0:
            return res
        # 查找相关数据
        res = self.get_initial()
        if len(res) > 0:
            return res

        return None


    def get_perfect(self):
        '''查询完全匹配情况数据'''
        perfect = []
       # 判断关键字个数
        if len(self.keywords) == 1:
            keyword = self.keywords[0]
            # 查询是否是书名
            res = db.query(Book, {'name': keyword}, True)
            if res:
                perfect.append(res)
            # 查询是否是作者
            res = db.query(Book, {'author': keyword})
            if len(res) > 0:
                for re in res:
                    perfect.append(re)
            # 如果是其他关键词，比如完结，待定，等
        if len(self.keywords) == 2:
            # 判断是否输入的是书名加作者
            res = db.query(Book, {'name': self.keywords[0], 'author': self.keywords[1]}, True)
            if res: 
                perfect.append(res)
            res = db.query(Book, {'name': self.keywords[1], 'author': self.keywords[0]}, True)
            if res: 
                perfect.append(res)
            # 是其他组合

        return perfect
        

    def get_initial(self):
        '''没有完全匹配数据时搜索相关数据'''
        initial = []
        if len(self.keywords) == 1:
            keyword = '%'+self.keywords[0]+'%'
            # 查询书名相关
            res = db.fuzzy_query(Book, {Book.name.like(keyword)})
            if len(res) > 0:
                for re in res:
                    initial.append(re)
            # 查询作者相关
            res = db.fuzzy_query(Book, {Book.author.like(keyword)})
            if len(res) > 0:
                for re in res:
                    initial.append(re)
            # 查询类别相关
            res = db.fuzzy_query(Book, {Book.booktype.like(keyword)})
            if len(res) > 0:
                for re in res:
                    initial.append(re)
        if len(self.keywords) == 2:
            k1 = '%' + self.keywords[0] + '%'
            k2 = '%' + self.keywords[1] + '%'

            # 如果是书名和作者
            res = db.fuzzy_query(Book, {Book.name.like(k1), Book.author.like(k2)})
            if len(res):
                for re in res:
                    initial.append(re)
            res = db.fuzzy_query(Book, {Book.name.like(k2), Book.author.like(k1)})
            if len(res):
                for re in res:
                    initial.append(re)
            # 如果是类别和书名
            res = db.fuzzy_query(Book, {Book.booktype.like(k1), Book.name.like(k2)})
            if len(res):
                for re in res:
                    initial.append(re)
            res = db.fuzzy_query(Book, {Book.booktype.like(k2), Book.name.like(k1)})
            if len(res):
                for re in res:
                    initial.append(re)

        return initial



# 把取得的小说对象转换成想要的数据格式返回
def to_dict(res):
    books = []
    for re in res:
        if bool(re):
            book = {}
            book['id'] = re.Id
            book['name'] = re.name
            book['author'] = re.author
            book['showUrl'] = re.showUrl
            book['describe'] = re.describe
            books.append(book)

    return books

def get_recommend(url):
    '''获取推荐数据的函数'''
    if 'booktxt.com' in url:
        booktxt = reptile.Booktxt()
        ids = booktxt.get_com_recommend()
        books = []
        for book_id in ids:
            book = db.query(Book, {'Id': book_id}, True)
            books.append(book)
        return books
    return None

def get_permission(user_id):
    '''查询当前用户的权限级别'''

    res = db.query(UserInfo, {'InfoId': user_id}, True)

    if bool(res):
        return res.permission
    return None

def set_admin():
    '''初始化设置一个超级管理员'''
    user_dict = {
        'username': 'admin',
        'password': get_md5('first_ppfadmin'), # first_ppfadmin
        'email' : 'kl_wj_lalala@163.com'
    }

    res, e = db.addone(User, user_dict)

    if res:
        # 添加用户详细信息
        print('=' * 10, '添加用户信息')
        res = db.query(User, user_dict, True)
        info_id = res.Id
        print(info_id)
        user_info = {
            'InfoId' : info_id,
            'permission': '5',
            'avatar' : None,
            'registDate': None,
            'loginDate' : None,
            'collect' : None,
            'down' : None,
            'noShow' : None,
            'state' : '离线',
            'remarks' : None
        }

        res, e = db.addone(UserInfo, user_info)
    return res

# 
def get_type(booktype):
    '''
    判断数据库里面有没有某个特定的类型，有的话取得该类型的所有书籍
    '''
    res = db.fuzzy_query(Book, {Book.booktype.like('%{0}%'.format(booktype))})
    if len(res) > 0:
        return res
    else:
        return None

def iscollect(user_id, book_id, isadd=False):
    '''判断用户是否收藏此书'''
    # 得到此用户收藏的所有书籍
    res = db.query(UserInfo, {'InfoId': user_id}, True)
    collects = str(res.collect).split('|')
    if str(book_id) in collects:
        return True

    # 根据参数判断是否需要添加藏书
    if isadd:
        # 添加到用户藏书
        res = db.query(UserInfo, {'InfoId' : user_id}, True)
        collect = str(book_id)
        if len(str(res.collect).split('|')) > 0: # 判断用户之前是否已经有藏书了
            collect = '%s|%s' % (res.collect, book_id)

        res, e = db.change(UserInfo, {'collect': collect}, {'InfoId' : user_id})
        return res
    return False

def start_spider(url):
    '''开始爬虫的方法'''
    try:
        p = multiprocessing.Process(
            name='xiaoshuo-spider',
            target=run_spider,
            args=('booktxt',),
            daemon=False
        )
        p.start()
        p.join()
        # run_spider('booktxt')
    except Exception as e:
        print('error', e)
        return False
    return True

# 判断有没有用户，如果没有一个用户就默认添加一个超级用户
res = db.query(User)
if len(res) <= 0:
    e = set_admin()
    print('=' * 10, e)